package com.yu.yupicture.manger.websocket;

import com.yu.yupicture.model.domain.entry.Picture;
import com.yu.yupicture.model.domain.entry.Space;
import com.yu.yupicture.model.enums.SpaceTypeEnum;
import com.yu.yupicture.service.PictureService;
import com.yu.yupicture.service.SpaceService;
import com.yu.yupicture.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * websocket拦截器
 */
@Slf4j
@Component
public class WsHandshakeInterceptor implements HandshakeInterceptor {
    @Resource
    private PictureService pictureService;
    @Resource
    private SpaceService spaceService;
    @Resource
    private UserService userService;

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        //从上下文中获取信息
        HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
        //获取请求参数
        String pictureId = servletRequest.getParameter("pictureId");
        if (pictureId == null) {
            log.error("缺少图片参数，拒绝连接");
            return false;
        }
        //获取图片信息
        Picture picture = pictureService.getById(pictureId);
        if (picture == null) {
            log.error("图片不存在，拒绝连接");
            return false;
        }
        //获取图片空间 id
        Long spaceId = picture.getSpaceId();
        if (spaceId != null) {
            //获取空间信息，并判断空间类型
            Space space = spaceService.getById(spaceId);
            if (space == null) {
                log.error("空间不存在，拒绝连接");
                return false;
            }
            if (space.getSpaceType().equals(SpaceTypeEnum.PRIVATE.getValue())) {
                log.error("空间类型错误，拒绝连接");
                return false;
            }
        }
        //todo 校验权限

        attributes.put("pictureId", pictureId);
        attributes.put("user", userService.getById(picture.getUserId()));
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

    }
}
